{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "# 批量归一化\n",
    "\n",
    "本节我们介绍批量归一化（batch normalization）层，它能让较深的神经网络的训练变得更加容易 [1]。在 [“实战Kaggle比赛：预测房价”](../chapter_deep-learning-basics/kaggle-house-price.ipynb) 一节里，我们对输入数据做了标准化处理：处理后的任意一个特征在数据集中所有样本上的均值为0、标准差为1。标准化处理输入数据使各个特征的分布相近：这往往更容易训练出有效的模型。\n",
    "\n",
    "通常来说，数据标准化预处理对于浅层模型就足够有效了。随着模型训练的进行，当每层中参数更新时，靠近输出层的输出较难出现剧烈变化。但对深层神经网络来说，即使输入数据已做标准化，训练中模型参数的更新依然很容易造成靠近输出层输出的剧烈变化。这种计算数值的不稳定性通常令我们难以训练出有效的深度模型。\n",
    "\n",
    "批量归一化的提出正是为了应对深度模型训练的挑战。在模型训练时，批量归一化利用小批量上的均值和标准差，不断调整神经网络中间输出，从而使整个神经网络在各层的中间输出的数值更稳定。批量归一化和下一节将要介绍的残差网络为训练和设计深度模型提供了两类重要思路。\n",
    "\n",
    "\n",
    "## 批量归一化层\n",
    "\n",
    "对全连接层和卷积层做批量归一化的方法稍有不同。下面我们将分别介绍这两种情况下的批量归一化。\n",
    "\n",
    "### 对全连接层做批量归一化\n",
    "\n",
    "我们先考虑如何对全连接层做批量归一化。通常，我们将批量归一化层置于全连接层中的仿射变换和激活函数之间。设全连接层的输入为$\\boldsymbol{u}$，权重参数和偏差参数分别为$\\boldsymbol{W}$和$\\boldsymbol{b}$，激活函数为$\\phi$。设批量归一化的运算符为$\\text{BN}$。那么，使用批量归一化的全连接层的输出为\n",
    "\n",
    "$$\\phi(\\text{BN}(\\boldsymbol{x})),$$\n",
    "\n",
    "其中批量归一化输入$\\boldsymbol{x}$由仿射变换\n",
    "\n",
    "$$\\boldsymbol{x} = \\boldsymbol{W\\boldsymbol{u} + \\boldsymbol{b}}$$\n",
    "\n",
    "得到。考虑一个由$m$个样本组成的小批量，仿射变换的输出为一个新的小批量$\\mathcal{B} = \\{\\boldsymbol{x}^{(1)}, \\ldots, \\boldsymbol{x}^{(m)} \\}$。它们正是批量归一化层的输入。对于小批量$\\mathcal{B}$中任意样本$\\boldsymbol{x}^{(i)} \\in \\mathbb{R}^d, 1 \\leq  i \\leq m$，批量归一化层的输出同样是$d$维向量\n",
    "\n",
    "$$\\boldsymbol{y}^{(i)} = \\text{BN}(\\boldsymbol{x}^{(i)}),$$\n",
    "\n",
    "并由以下几步求得。首先，对小批量$\\mathcal{B}$求均值和方差：\n",
    "\n",
    "$$\\boldsymbol{\\mu}_\\mathcal{B} \\leftarrow \\frac{1}{m}\\sum_{i = 1}^{m} \\boldsymbol{x}^{(i)},$$\n",
    "$$\\boldsymbol{\\sigma}_\\mathcal{B}^2 \\leftarrow \\frac{1}{m} \\sum_{i=1}^{m}(\\boldsymbol{x}^{(i)} - \\boldsymbol{\\mu}_\\mathcal{B})^2,$$\n",
    "\n",
    "其中的平方计算是按元素求平方。接下来，使用按元素开方和按元素除法对$\\boldsymbol{x}^{(i)}$标准化：\n",
    "\n",
    "$$\\hat{\\boldsymbol{x}}^{(i)} \\leftarrow \\frac{\\boldsymbol{x}^{(i)} - \\boldsymbol{\\mu}_\\mathcal{B}}{\\sqrt{\\boldsymbol{\\sigma}_\\mathcal{B}^2 + \\epsilon}},$$\n",
    "\n",
    "这里$\\epsilon > 0$是一个很小的常数，保证分母大于0。在上面标准化的基础上，批量归一化层引入了两个可以学习的模型参数，拉伸（scale）参数 $\\boldsymbol{\\gamma}$ 和偏移（shift）参数 $\\boldsymbol{\\beta}$。这两个参数和$\\boldsymbol{x}^{(i)}$形状相同，皆为$d$维向量。它们与$\\hat{\\boldsymbol{x}}^{(i)}$分别做按元素乘法（符号$\\odot$）和加法计算：\n",
    "\n",
    "$${\\boldsymbol{y}}^{(i)} \\leftarrow \\boldsymbol{\\gamma} \\odot \\hat{\\boldsymbol{x}}^{(i)} + \\boldsymbol{\\beta}.$$\n",
    "\n",
    "至此，我们得到了$\\boldsymbol{x}^{(i)}$的批量归一化的输出$\\boldsymbol{y}^{(i)}$。\n",
    "值得注意的是，可学习的拉伸和偏移参数保留了不对$\\boldsymbol{x}^{(i)}$做批量归一化的可能：此时只需学出$\\boldsymbol{\\gamma} = \\sqrt{\\boldsymbol{\\sigma}_\\mathcal{B}^2 + \\epsilon}$和$\\boldsymbol{\\beta} = \\boldsymbol{\\mu}_\\mathcal{B}$。我们可以对此这样理解：如果批量归一化无益，理论上，学出的模型可以不使用批量归一化。\n",
    "\n",
    "\n",
    "### 对卷积层做批量归一化\n",
    "\n",
    "对卷积层来说，批量归一化发生在卷积计算之后、应用激活函数之前。如果卷积计算输出多个通道，我们需要对这些通道的输出分别做批量归一化，且每个通道都拥有独立的拉伸和偏移参数，并均为标量。设小批量中有$m$个样本。在单个通道上，假设卷积计算输出的高和宽分别为$p$和$q$。我们需要对该通道中$m \\times p \\times q$个元素同时做批量归一化。对这些元素做标准化计算时，我们使用相同的均值和方差，即该通道中$m \\times p \\times q$个元素的均值和方差。\n",
    "\n",
    "\n",
    "### 预测时的批量归一化\n",
    "\n",
    "使用批量归一化训练时，我们可以将批量大小设得大一点，从而使批量内样本的均值和方差的计算都较为准确。将训练好的模型用于预测时，我们希望模型对于任意输入都有确定的输出。因此，单个样本的输出不应取决于批量归一化所需要的随机小批量中的均值和方差。一种常用的方法是通过移动平均估算整个训练数据集的样本均值和方差，并在预测时使用它们得到确定的输出。可见，和丢弃层一样，批量归一化层在训练模式和预测模式下的计算结果也是不一样的。\n",
    "\n",
    "\n",
    "## 从零开始实现\n",
    "\n",
    "下面我们通过`NDArray`来实现批量归一化层。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import numpy as np\r\n",
    "import paddle\r\n",
    "import paddle.nn as nn\r\n",
    "import paddle.fluid.layers as layers\r\n",
    "\r\n",
    "def batch_norm(X, gamma, beta, moving_mean, moving_var, eps, momentum, is_training=True):\r\n",
    "    # 训练模式还与预测模式的BN处理不同\r\n",
    "    if not is_training:\r\n",
    "        # 如果是在预测模式下，直接使用传入的移动平均所得的均值和方差\r\n",
    "        X_hat = (X - moving_mean) / (moving_var + eps) ** 0.5\r\n",
    "    else:\r\n",
    "        assert len(X.shape) in (2, 4)\r\n",
    "        if len(X.shape) == 2:\r\n",
    "            # 使用全连接层的情况，计算特征维上的均值和方差\r\n",
    "            mean = paddle.mean(X)\r\n",
    "            var = paddle.mean(((X - mean) ** 2))\r\n",
    "        else:\r\n",
    "            # 使用二维卷积层的情况，计算通道维上（axis=1）的均值和方差。这里我们需要保持\r\n",
    "            # X的形状以便后面可以做广播运算\r\n",
    "            mean = paddle.mean(X, axis=(0, 2, 3), keepdim=True)\r\n",
    "            var = paddle.mean(((X - mean) ** 2), axis=(0, 2, 3), keepdim=True)\r\n",
    "        # 训练模式下用当前的均值和方差做标准化\r\n",
    "        X_hat = (X - mean) / (var + eps) ** 0.5\r\n",
    "        # 更新移动平均的均值和方差\r\n",
    "        moving_mean = momentum * moving_mean + (1.0 - momentum) * mean\r\n",
    "        moving_var = momentum * moving_var + (1.0 - momentum) * var\r\n",
    "    Y = gamma * X_hat + beta  # 拉伸和偏移\r\n",
    "    return Y, moving_mean, moving_var\r\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "接下来，我们自定义一个`BatchNorm`层。它保存参与求梯度和迭代的拉伸参数`gamma`和偏移参数`beta`，同时也维护移动平均得到的均值和方差，以便能够在模型预测时被使用。`BatchNorm`实例所需指定的`num_features`参数对于全连接层来说应为输出个数，对于卷积层来说则为输出通道数。该实例所需指定的`num_dims`参数对于全连接层和卷积层来说分别为2和4。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class BatchNorm(nn.Layer):\r\n",
    "    def __init__(self, num_features, num_dims=4):\r\n",
    "        super(BatchNorm, self).__init__()\r\n",
    "        if num_dims == 2:\r\n",
    "            shape = (1, num_features)\r\n",
    "        else:\r\n",
    "            shape = (1, num_features, 1, 1)\r\n",
    "        # 参与求梯度和迭代的拉伸和偏移参数，分别初始化成1和0\r\n",
    "        self.gamma = self.create_parameter(\r\n",
    "            attr=None,\r\n",
    "            shape=shape,\r\n",
    "            dtype='float32',\r\n",
    "            is_bias=False,\r\n",
    "            default_initializer=nn.initializer.Assign(paddle.ones(shape=shape, dtype='float32')))\r\n",
    "        self.beta = self.create_parameter(\r\n",
    "            attr=None,\r\n",
    "            shape=shape,\r\n",
    "            dtype='float32',\r\n",
    "            is_bias=False,\r\n",
    "            default_initializer=nn.initializer.Assign(paddle.zeros(shape=shape, dtype='float32')))\r\n",
    "        self.moving_mean = paddle.zeros(shape=shape, dtype='float32')\r\n",
    "        self.moving_var = paddle.zeros(shape=shape, dtype='float32')\r\n",
    "\r\n",
    "    def forward(self, X):\r\n",
    "        # 保存更新过的moving_mean和moving_var\r\n",
    "        Y, self.moving_mean, self.moving_var = batch_norm(\r\n",
    "            X, self.gamma, self.beta, self.moving_mean,\r\n",
    "            self.moving_var, eps=1e-5, momentum=0.9, is_training=self.training)\r\n",
    "        return Y\r\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "### 使用批量归一化层的LeNet\n",
    "\n",
    "下面我们修改[“卷积神经网络（LeNet）”](lenet.ipynb)这一节介绍的LeNet模型，从而应用批量归一化层。我们在所有的卷积层或全连接层之后、激活层之前加入批量归一化层。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class LeNet(nn.Layer):\r\n",
    "    def __init__(self, num_dim=1, num_class=10):\r\n",
    "        super(LeNet, self).__init__()\r\n",
    "        self.conv1 = nn.Conv2D(num_dim, 6, 5)\r\n",
    "        self.bn1 = BatchNorm(6, num_dims=4)\r\n",
    "        self.pool1 = nn.MaxPool2D(2, stride=2)\r\n",
    "        self.conv2 = nn.Conv2D(6, 16, 5)\r\n",
    "        self.bn2 = BatchNorm(16, num_dims=4)\r\n",
    "        self.pool2 = nn.MaxPool2D(2, stride=2)\r\n",
    "        self.fc1 = nn.Linear(256, 120)\r\n",
    "        self.bn3 = BatchNorm(120, num_dims=2)\r\n",
    "        self.fc2 = nn.Linear(120, 84)\r\n",
    "        self.bn4 = BatchNorm(84, num_dims=2)\r\n",
    "        self.fc3 = nn.Linear(84, num_class)\r\n",
    "    def forward(self, X):\r\n",
    "        Y = self.conv1(X)\r\n",
    "        Y = layers.sigmoid(self.bn1(Y))\r\n",
    "        Y = self.pool1(Y)\r\n",
    "        Y = self.conv2(Y)\r\n",
    "        Y = layers.sigmoid(self.bn2(Y))\r\n",
    "        Y = self.pool2(Y)\r\n",
    "        Y = paddle.flatten(Y, start_axis=1)\r\n",
    "        Y = self.fc1(Y)\r\n",
    "        Y = layers.sigmoid(self.bn3(Y))\r\n",
    "        Y = self.fc2(Y)\r\n",
    "        Y = layers.sigmoid(self.bn4(Y))\r\n",
    "        Y = self.fc3(Y)\r\n",
    "        return Y\r\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "下面我们训练修改后的模型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/2\n",
      "step 200/938 - loss: 0.7530 - acc_top1: 0.7381 - acc_top5: 0.9295 - 93ms/step\n",
      "step 400/938 - loss: 0.2493 - acc_top1: 0.8325 - acc_top5: 0.9630 - 93ms/step\n",
      "step 600/938 - loss: 0.1861 - acc_top1: 0.8708 - acc_top5: 0.9746 - 93ms/step\n",
      "step 800/938 - loss: 0.0885 - acc_top1: 0.8927 - acc_top5: 0.9806 - 93ms/step\n",
      "step 938/938 - loss: 0.1341 - acc_top1: 0.9028 - acc_top5: 0.9832 - 92ms/step\n",
      "Epoch 2/2\n",
      "step 200/938 - loss: 0.1882 - acc_top1: 0.9670 - acc_top5: 0.9987 - 92ms/step\n",
      "step 400/938 - loss: 0.1249 - acc_top1: 0.9670 - acc_top5: 0.9988 - 92ms/step\n",
      "step 600/938 - loss: 0.1083 - acc_top1: 0.9678 - acc_top5: 0.9991 - 93ms/step\n",
      "step 800/938 - loss: 0.0616 - acc_top1: 0.9683 - acc_top5: 0.9991 - 93ms/step\n",
      "step 938/938 - loss: 0.0312 - acc_top1: 0.9689 - acc_top5: 0.9992 - 93ms/step\n",
      "Eval begin...\n",
      "step 157/157 - loss: 0.0181 - acc_top1: 0.9789 - acc_top5: 0.9994 - 18ms/step\n",
      "Eval samples: 10000\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'loss': [0.018111179], 'acc_top1': 0.9789, 'acc_top5': 0.9994}"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train_dataset = paddle.vision.datasets.MNIST(mode='train')\r\n",
    "test_dataset = paddle.vision.datasets.MNIST(mode='test')\r\n",
    "train_loader = paddle.io.DataLoader(train_dataset, places=paddle.CPUPlace(), batch_size=128, shuffle=True)\r\n",
    "# train_loader = paddle.io.DataLoader(train_dataset, places=paddle.CUDAPlace(0), batch_size=128, shuffle=True)\r\n",
    "lenet = LeNet()\r\n",
    "model = paddle.Model(lenet)\r\n",
    "# 设置训练模型所需的optimizer, loss, metric\r\n",
    "model.prepare(\r\n",
    "    paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters()),\r\n",
    "    paddle.nn.CrossEntropyLoss(),\r\n",
    "    paddle.metric.Accuracy(topk=(1, 5))\r\n",
    ")\r\n",
    "# 启动训练\r\n",
    "model.fit(train_dataset, epochs=2, batch_size=64, log_freq=200)\r\n",
    "# 启动评估\r\n",
    "model.evaluate(test_dataset, batch_size=64, log_freq=200)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "最后我们查看第一个批量归一化层学习到的拉伸参数`gamma`和偏移参数`beta`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "gamma: [0.9993303  1.2117258  0.9204261  1.2410485  0.96498287 1.0638356 ]\n",
      "beta: [-0.6617338   0.36482725 -0.37912193 -0.84046793  0.03642483 -0.4232367 ]\n"
     ]
    }
   ],
   "source": [
    "param = model.parameters()\r\n",
    "print('gamma:', param[2].numpy().reshape(-1))\r\n",
    "print('beta:', param[3].numpy().reshape(-1))\r\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 简洁实现\n",
    "\n",
    "与我们刚刚自己定义的`BatchNorm`类相比，Paddle中`nn`模块定义的`BatchNorm`类使用起来更加简单。它不需要指定自己定义的`BatchNorm`类中所需的`num_features`和`num_dims`参数值。在Paddle中，这些参数值都将通过延后初始化而自动获取。下面我们用Paddle实现使用批量归一化的LeNet。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class LeNet(nn.Layer):\r\n",
    "    def __init__(self, num_dim=1, num_class=10):\r\n",
    "        super(LeNet, self).__init__()\r\n",
    "        model_conv = [\r\n",
    "            nn.Conv2D(num_dim, 6, 5),\r\n",
    "            # nn.BatchNorm(6),\r\n",
    "            nn.Sigmoid(),\r\n",
    "            nn.MaxPool2D(2, stride=2),\r\n",
    "            nn.Conv2D(6, 16, 5),\r\n",
    "            # nn.BatchNorm(16),\r\n",
    "            nn.MaxPool2D(2, stride=2),\r\n",
    "            nn.Sigmoid(),\r\n",
    "        ]\r\n",
    "        self.model_conv = nn.Sequential(*model_conv)\r\n",
    "        model_fc = [\r\n",
    "            nn.Linear(256, 120),\r\n",
    "            # nn.BatchNorm(120),\r\n",
    "            nn.Sigmoid(),\r\n",
    "            nn.Linear(120, 84),\r\n",
    "            # nn.BatchNorm(84),\r\n",
    "            nn.Sigmoid(),\r\n",
    "            nn.Linear(84, num_class),\r\n",
    "        ]\r\n",
    "        self.model_fc = nn.Sequential(*model_fc)\r\n",
    "    def forward(self, X):\r\n",
    "        Y = self.model_conv(X)\r\n",
    "        Y = paddle.flatten(Y, start_axis=1)\r\n",
    "        Y = self.model_fc(Y)\r\n",
    "        return Y\r\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "使用同样的超参数进行训练。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/2\n",
      "step 200/938 - loss: 1.2379 - acc_top1: 0.3711 - acc_top5: 0.7719 - 18ms/step\n",
      "step 400/938 - loss: 0.4238 - acc_top1: 0.6150 - acc_top5: 0.8818 - 17ms/step\n",
      "step 600/938 - loss: 0.4075 - acc_top1: 0.7167 - acc_top5: 0.9199 - 17ms/step\n",
      "step 800/938 - loss: 0.1410 - acc_top1: 0.7715 - acc_top5: 0.9394 - 17ms/step\n",
      "step 938/938 - loss: 0.1625 - acc_top1: 0.7972 - acc_top5: 0.9480 - 17ms/step\n",
      "Epoch 2/2\n",
      "step 200/938 - loss: 0.1327 - acc_top1: 0.9528 - acc_top5: 0.9984 - 17ms/step\n",
      "step 400/938 - loss: 0.1168 - acc_top1: 0.9544 - acc_top5: 0.9985 - 17ms/step\n",
      "step 600/938 - loss: 0.1193 - acc_top1: 0.9563 - acc_top5: 0.9986 - 17ms/step\n",
      "step 800/938 - loss: 0.0984 - acc_top1: 0.9587 - acc_top5: 0.9988 - 17ms/step\n",
      "step 938/938 - loss: 0.0507 - acc_top1: 0.9595 - acc_top5: 0.9989 - 17ms/step\n",
      "Eval begin...\n",
      "step 157/157 - loss: 0.0298 - acc_top1: 0.9689 - acc_top5: 0.9996 - 8ms/step\n",
      "Eval samples: 10000\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'loss': [0.029764377], 'acc_top1': 0.9689, 'acc_top5': 0.9996}"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "train_dataset = paddle.vision.datasets.MNIST(mode='train')\n",
    "test_dataset = paddle.vision.datasets.MNIST(mode='test')\n",
    "train_loader = paddle.io.DataLoader(train_dataset, places=paddle.CPUPlace(), batch_size=128, shuffle=True)\n",
    "# train_loader = paddle.io.DataLoader(train_dataset, places=paddle.CUDAPlace(0), batch_size=128, shuffle=True)\n",
    "lenet = LeNet()\n",
    "model = paddle.Model(lenet)\n",
    "# 设置训练模型所需的optimizer, loss, metric\n",
    "model.prepare(\n",
    "    paddle.optimizer.Adam(learning_rate=0.001, parameters=model.parameters()),\n",
    "    paddle.nn.CrossEntropyLoss(),\n",
    "    paddle.metric.Accuracy(topk=(1, 5))\n",
    ")\n",
    "# 启动训练\n",
    "model.fit(train_dataset, epochs=2, batch_size=64, log_freq=200)\n",
    "# 启动评估\n",
    "model.evaluate(test_dataset, batch_size=64, log_freq=200)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## 小结\n",
    "\n",
    "* 在模型训练时，批量归一化利用小批量上的均值和标准差，不断调整神经网络的中间输出，从而使整个神经网络在各层的中间输出的数值更稳定。\n",
    "* 对全连接层和卷积层做批量归一化的方法稍有不同。\n",
    "* 批量归一化层和丢弃层一样，在训练模式和预测模式的计算结果是不一样的。\n",
    "* Paddle提供的BatchNorm类使用起来简单、方便。\n",
    "\n",
    "## 练习\n",
    "\n",
    "* 能否将批量归一化前的全连接层或卷积层中的偏差参数去掉？为什么？（提示：回忆批量归一化中标准化的定义。）\n",
    "* 尝试调大学习率。同[“卷积神经网络（LeNet）”](lenet.ipynb)一节中未使用批量归一化的LeNet相比，现在是不是可以使用更大的学习率？\n",
    "* 尝试将批量归一化层插入LeNet的其他地方，观察并分析结果的变化。\n",
    "* 尝试一下不学习拉伸参数`gamma`和偏移参数`beta`（构造的时候加入参数`grad_req='null'`来避免计算梯度），观察并分析结果。\n",
    "* 查看`BatchNorm`类的文档来了解更多使用方法，例如，如何在训练时使用基于全局平均的均值和方差。\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "## 参考文献\n",
    "\n",
    "[1] Ioffe, S., & Szegedy, C. (2015). Batch normalization: Accelerating deep network training by reducing internal covariate shift. arXiv preprint arXiv:1502.03167.\n",
    "\n",
    "## 扫码直达[讨论区](https://discuss.gluon.ai/t/topic/1253)\n",
    "\n",
    "![](../img/qr_batch-norm.svg)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "PaddlePaddle 2.0.0b0 (Python 3.5)",
   "language": "python",
   "name": "py35-paddle1.2.0"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
